package bean;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderableOp;
import javax.media.jai.RenderedOp;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class MemberDTO {

	private MemberVo vo;
	private Connection conn;

	// 페이지와 관련된 변수
	int listSize = 5; // 페이지당 표시되는 행수
	int blockSize = 3; // 한블럭당 표시되는 페이지수
	int totSize = 0; // 전체 게시물의 갯수
	int totPage = 0; // 전체 페이지수
	int totBlock = 0; // 전체 블럭수
	int nowPage = 1; // 현재페이지
	int nowBlock = 1; // 현재 블럭
	int startNo = 0; // 리스트 목록의 시작 위치
	int endNo = 0; // 리스트 목록의 끝 위치
	int startPage = 0; // 현재블럭에서 표시되는 시작 블럭번호
	int endPage = 0; // 현재블럭에서 표시되는 끝 블럭 번호

	String saveDir = "H:/workspace/web_1406/WebContent/memberPhoto/";
	
	public MemberDTO() {
		conn = new MyOracle().getConn();
	}

	public boolean login() {
		boolean b = false;
		try {
			String sql = "select mid, pwd from member where mid=? and pwd=?";
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getMid());
			pst.setString(2, vo.getPwd());

			ResultSet rs = pst.executeQuery();
			if (rs.next())
				b = true;

			pst.close();
			conn.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return b;
	}

	public void page() {// 페이지관련 연산
		String sql = "select count(*) cnt from member "
				+ " where mid like ? or irum like ? or phone like ? or address like ? ";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%" + vo.getFind() + "%");
			pst.setString(2, "%" + vo.getFind() + "%");
			pst.setString(3, "%" + vo.getFind() + "%");
			pst.setString(4, "%" + vo.getFind() + "%");

			ResultSet rs = pst.executeQuery();
			if (rs.next()) {
				totSize = rs.getInt("cnt");
				// 전체 페이지수
				totPage = (int) Math.ceil(totSize * 1.0 / listSize);
				// 전체 블럭수
				totBlock = (int) Math.ceil(totPage * 1.0 / blockSize);
				// 현재 블럭
				nowBlock = (int) Math.ceil(nowPage * 1.0 / blockSize);

				// 페이지의 시작과끝 번호
				endPage = nowBlock * blockSize;
				startPage = endPage - blockSize + 1;
				// 게시물의 시작번호와 끝 번호
				endNo = nowPage * listSize;
				startNo = endNo - listSize + 1;
				// endPage, endNo 보정값
				if (endPage > totPage)
					endPage = totPage;
				if (endNo > totSize)
					endNo = totSize;

			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void setVo(MemberVo vo) {
		this.vo = vo;
		this.nowBlock = vo.getNowBlock();
		this.nowPage = vo.getNowPage();
	}

	public void setVo2(MemberVo vo) {
		if (vo.getRequest() == null)
			return;
		this.vo = vo;
		int size = 1024 * 1024 * 10;
		String oriFile = "";
		String sysFile = "";

		MultipartRequest multi = null;
		try {
			multi = new MultipartRequest(vo.getRequest(), saveDir, size,
					"utf-8", new DefaultFileRenamePolicy());

			Enumeration files = multi.getFileNames();
			String tempFile = (String) files.nextElement();

			oriFile = multi.getOriginalFileName(tempFile);
			sysFile = multi.getFilesystemName(tempFile);

			vo.setMid(multi.getParameter("mid"));
			vo.setIrum(multi.getParameter("irum"));
			vo.setPwd(multi.getParameter("pwd"));
			vo.setOldPhoto(multi.getParameter("oldPhoto"));
			vo.setNowPage(Integer.parseInt(multi.getParameter("nowPage")));
			vo.setFind(multi.getParameter("find"));
			vo.setPhoto(sysFile);
			
			//섬네일 파일 추가 생성
			ParameterBlock pd = new ParameterBlock();
			pd.add(saveDir + sysFile);
			RenderedOp rOp = JAI.create("fileload", pd);
			
			BufferedImage bi=rOp.getAsBufferedImage();
			BufferedImage thumb = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
			Graphics2D g=thumb.createGraphics();
			g.drawImage(bi,0,0,100,100,null);
			
			File file = new File(saveDir + "sm_" + sysFile);
			ImageIO.write(thumb, "png", file);
			

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	public boolean insert() {
		boolean b = false;
		String sql = "insert into member(mid, irum, photo) values(?,?,?)";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getMid());
			pst.setString(2, vo.getIrum());
			pst.setString(3, vo.getPhoto());
			int cnt = pst.executeUpdate();
			if (cnt > 0)
				b = true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return b;
	}

	public ArrayList<MemberVo> select() {
		page();
		ArrayList<MemberVo> al = new ArrayList<>();
		String sql = " select * from("
				+ "   select rownum rn, c.* from( "
				+ "     select * from member "
				+ "     where mid like ? or irum like ? or phone like ? or address like ?  )c "
				+ "   )b " + " where b.rn between ? and ? ";

		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%" + vo.getFind() + "%");
			pst.setString(2, "%" + vo.getFind() + "%");
			pst.setString(3, "%" + vo.getFind() + "%");
			pst.setString(4, "%" + vo.getFind() + "%");

			pst.setInt(5, startNo);
			pst.setInt(6, endNo);

			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				MemberVo v = new MemberVo();
				v.setMid(rs.getString("mid"));
				v.setIrum(rs.getString("irum"));
				v.setPhoto(rs.getString("photo"));
				al.add(v);
			}

			rs.close();
			pst.close();
			conn.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return al;
	}

	public MemberVo selectOne() {
		MemberVo v = new MemberVo();
		String sql = "select * from member where mid=?";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getMid());
			ResultSet rs = pst.executeQuery();
			if (rs.next()) {
				v.setMid(rs.getString("mid"));
				v.setPhoto(rs.getString("photo"));
				v.setIrum(rs.getString("irum"));
				v.setNowPage(vo.getNowPage());
				v.setFind(vo.getFind());
			}
			rs.close();
			pst.close();
			conn.close();
		} catch (Exception ex) {

		}
		return v;
	}

	public boolean modify() {
		boolean b = false;
		String sql = "";
		PreparedStatement pst = null;
		try {
			if (vo.getPhoto()==null) {
				sql = "update member set irum=?  where mid=?";
				pst = conn.prepareStatement(sql);
				pst.setString(1, vo.getIrum());
				pst.setString(2, vo.getMid());
			} else {
				sql = "update member set irum=? , photo=? where mid=?";
				pst = conn.prepareStatement(sql);
				pst.setString(1, vo.getIrum());
				pst.setString(2, vo.getPhoto());
				pst.setString(3, vo.getMid());
				
				File f = new File(saveDir + vo.getOldPhoto());
				System.out.println(f.getPath());
				if (f.exists())
					f.delete();
			}
			int cnt = pst.executeUpdate();
			if(cnt>0) b=true;
			
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return b;
	}

	public boolean delete() {
		boolean b = false;
		String sql = "delete from member where mid=?";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getMid());
			int cnt = pst.executeUpdate();
			if (cnt > 0) {
				b = true;
				
				File f = new File(saveDir + vo.getPhoto());
				System.out.println(f.getPath());
				if (f.exists())
					f.delete();
			}

			pst.close();
			conn.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return b;
	}

	public int getListSize() {
		return listSize;
	}

	public void setListSize(int listSize) {
		this.listSize = listSize;
	}

	public int getBlockSize() {
		return blockSize;
	}

	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}

	public int getTotSize() {
		return totSize;
	}

	public void setTotSize(int totSize) {
		this.totSize = totSize;
	}

	public int getTotPage() {
		return totPage;
	}

	public void setTotPage(int totPage) {
		this.totPage = totPage;
	}

	public int getTotBlock() {
		return totBlock;
	}

	public void setTotBlock(int totBlock) {
		this.totBlock = totBlock;
	}

	public int getNowPage() {
		return nowPage;
	}

	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}

	public int getNowBlock() {
		return nowBlock;
	}

	public void setNowBlock(int nowBlock) {
		this.nowBlock = nowBlock;
	}

	public int getStartNo() {
		return startNo;
	}

	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}

	public int getEndNo() {
		return endNo;
	}

	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}

	public int getStartPage() {
		return startPage;
	}

	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}

	public int getEndPage() {
		return endPage;
	}

	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}

	public MemberVo getVo() {
		return vo;
	}

}
